#pragma once
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <unistd.h>
#define NUM 1024
namespace client
{
    class TcpClient
    {
    public:
        TcpClient(const std::string &serverIp, const uint16_t &serverPort)
            : _sock(-1), _serverIp(serverIp), _serverPort(serverPort)
        {
        }

        void initClient()
        {
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if (_sock < 0)
            {
                std::cerr << "socket create error" << std::endl;
                exit(2);
            }
        }

        void start()
        {
            struct sockaddr_in server;
            bzero(&server, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverPort);
            server.sin_addr.s_addr = inet_addr(_serverIp.c_str());
            // 服务端在listen 客户端要去链接
            // int connect(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
            if (connect(_sock, (struct sockaddr *)&server, sizeof(server)) != 0)
            {
                std::cerr << "socket connect error" << std::endl;
            }
            else
            {
                std::string msg;
                // 链接成功
                while (true)
                {
                    std::cout << "Enter# ";
                    std::getline(std::cin, msg);
                    write(_sock, msg.c_str(), msg.size());

                    char buffer[NUM];
                    int n = read(_sock, buffer, sizeof(buffer) - 1);
                    if (n > 0)
                    {
                        // 目前我们把读到的数据当成字符串, 截止目前
                        buffer[n] = 0;
                        std::cout << "Server回显# " << buffer << std::endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        ~TcpClient()
        {
            if (_sock >= 0)
            {
                close(_sock);
            }      
        }

    private:
        int _sock;
        std::string _serverIp;
        uint16_t _serverPort;
    };
}